package cat.joronya.supermanager.service;

import java.util.ArrayList;
import java.util.List;

import org.htmlcleaner.ContentNode;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import android.util.Log;

import cat.joronya.supermanager.privateleague.PrivateLeague;

public class PrivateLeagueSearchParser 
{
	private static final String TAG = "supermanager";
	
	private static final String PRIVATE_LEAGUES_XPATH = "//table[@width='609']";
	
	public ArrayList<PrivateLeague> parse(String html) throws Exception
	{
		ArrayList<PrivateLeague> privateLeagues = new ArrayList<PrivateLeague>();

		HtmlCleaner cleaner = new HtmlCleaner();
		TagNode node = cleaner.clean(html);
		
		Object[] tables = node.evaluateXPath(PRIVATE_LEAGUES_XPATH);
		TagNode table = (TagNode)tables[1];
		TagNode tbody = table.getChildTags()[0];
		TagNode[] tbodyChilds = tbody.getChildTags();
		TagNode form = tbodyChilds[1];
		TagNode[] trs = form.getChildTags();
		
		// saltem el primer i els 3 ultims
		for(int i=0; i<trs.length; i++)
		{
			if( !(trs[i] instanceof TagNode) )
				continue;
			
			// tenen un unic td
			TagNode td = trs[i].getChildTags()[0];
			
			// els tds tenen 3 fills
			@SuppressWarnings("rawtypes")
			List tdChilds = td.getChildren();
			
			// el 2on el input radio amb el id_pri a enviar
			TagNode radio = (TagNode)tdChilds.get(1);
			
			// si no tenim un radio button al 2 element, continuem
			if( ! radio.getAttributeByName("type").equals("radio") )
				continue;
			
			// private league per guardar les dades i serialitzar-les
			PrivateLeague pl = new PrivateLeague();

			// guardem valor id_pri
			String idPri = radio.getAttributeByName("value");
			pl.setId(idPri);
			
			// el 3er child un ContentNode amb el nom
			ContentNode name = (ContentNode)tdChilds.get(2);
			pl.setName(name.toString());
			
			// guardem PL parsejada
			privateLeagues.add(pl);
		}
		
		// parsejat ok
		Log.d(TAG, "PrivateLeagueSearchParser: private league list parsed ok");
		return privateLeagues;
	}
}
